<?php
/*
 * @开发工具: JetBrains PhpStorm.
 * @文件名：User.php
 * @类功能: 用户操作类
 * @开发者: gys
 * @开发时间： 18-03-15
 * @版本：version 1.0
 */
namespace app\common\ext;

use app\admin\widget\Name;
use app\common\cache\user\IUserCache;
use app\common\enum\AgreeProtocol;
use app\common\enum\AssetPayType;
use app\common\enum\AuditStatus;
use app\common\enum\HolderType;
use app\common\enum\HouseType;
use app\common\enum\HtmlEnumValue;
use app\common\enum\IsAccumulationFund;
use app\common\enum\IsAssure;
use app\common\enum\IsCar;
use app\common\enum\IsCompany;
use app\common\enum\IsCreditCard;
use app\common\enum\IsDelete;
use app\common\enum\IsHistory;
use app\common\enum\IsHouse;
use app\common\enum\IsLoan;
use app\common\enum\IsMarry;
use app\common\enum\IsOverdue;
use app\common\enum\IsPolicy;
use app\common\enum\IsShop;
use app\common\enum\IsSocial;
use app\common\enum\IsStudent;
use app\common\enum\IsWhite;
use app\common\enum\LoanType;
use app\common\enum\PoolBidStatus;
use app\common\enum\PoolClaimStatus;
use app\common\enum\PoolVieStatus;
use app\common\enum\UserIntentionLevel;
use app\common\enum\PoolLevel;
use app\common\enum\UserPoolBidType;

class User extends ICommon {
    //个人资产类型
    const MATERIAL_COMPANY = 'company';
    const MATERIAL_HOUSE = 'house';
    const MATERIAL_CREDIT_CARD = 'credit_card';
    const MATERIAL_POLICY = 'policy';
    const MATERIAL_CAR = 'car';
    const MATERIAL_LOAN = 'loan';
    const MATERIAL_ASSURE = 'assure';
    const MATERIAL_SHOP = 'shop';
    const MATERIAL_OVERDUE = 'overdue';

    private static $asset_map = [
        self::MATERIAL_COMPANY => '公司',
        self::MATERIAL_HOUSE => '房产',
        self::MATERIAL_CREDIT_CARD => '信用卡',
        self::MATERIAL_POLICY => '保单',
        self::MATERIAL_CAR => '车辆',
        self::MATERIAL_LOAN => '贷款',
        self::MATERIAL_ASSURE => '担保',
        self::MATERIAL_SHOP => '网店',
        self::MATERIAL_OVERDUE => '逾期',
    ];

    /**
     * @功能 设置同意过贷款协议
     * @param $user_id int 用户编号
     * @param $post_body array 表单信息
     * @param $phone_info string 客户端信息 "|"隔开
     * @param $source string 客户端类型
     * @开发者：gys
     * @return string
     */
    public static function agree_protocol($user_id, $post_body, $phone_info, $source = null) {
        //取得用户是否同意过贷款协议
        $agree_protocol = IUserCache::getInfo($user_id,'agree_protocol');

        //判断是否需要修改
        if($agree_protocol == AgreeProtocol::No){
            //修改用户信息
            $user_where['user_id'] = $user_id;
            $user_data['agree_protocol'] = AgreeProtocol::Yes;
            $user_upd = IDb::getInstance("user")->setDbData($user_data)->setDbWhere($user_where)->upd();
            if($user_upd === false){
                return false;
            }

            $source = get_enum_name('source',$source);
            if(!empty($source)){
                $device_info = '客户端:'.$source;
            }else{
                $device_info = '客户端:未知';
            }
            if(!empty($phone_info)){
                $device_info .= '|'.$phone_info;
            }

            $agree_info['user_id'] = $user_id;
            $agree_info['post_head'] = json_encode(getallheaders(),JSON_UNESCAPED_UNICODE);;
            $agree_info['post_body'] = json_encode($post_body,JSON_UNESCAPED_UNICODE);
            $agree_info['post_ip'] = get_client_ip();
            $agree_info['phone_info'] = $device_info;
            $result = IDb::getInstance('user_agree_info')->setDbData($agree_info)->add();
            if($result === false){
                return false;
            }

            //清除用户缓存
            IUserCache::deleteInfo($user_id);
        }else{
            return null;
        }

        //返回值
        return true;
    }

    /**
     * @功能 同步用户数据到个人资产数据
     * @param $user_id int 用户编号
     * @param $user_data array 用户数据
     * @开发者：gys
     * @return string
     */
    public static function syncUserInfoToMaterial($user_id, $user_data){
        //修改公司数据为历史
        if(isset($user_data['is_company'])){
            $result = self::setMaterialHistory($user_id,self::MATERIAL_COMPANY,$user_data['is_company']);
            if($result === false){
                return false;
            }
        }

        //修改房产数据为历史
        if(isset($user_data['is_house'])){
            $result = self::setMaterialHistory($user_id,self::MATERIAL_HOUSE,$user_data['is_house']);
            if($result === false){
                return false;
            }
        }

        //修改信用卡数据为历史
        if(isset($user_data['is_credit_card'])){
            $result = self::setMaterialHistory($user_id,self::MATERIAL_CREDIT_CARD,$user_data['is_credit_card']);
            if($result === false){
                return false;
            }
        }

        //修改逾期信息
        if(isset($user_data['is_overdue'])){
//            $user_info = IUserCache::getInfo($user_id);
//            $user_data['overdue_info'] = ['exp','null'];
            $result = self::setMaterialHistory($user_id,self::MATERIAL_OVERDUE,$user_data['is_overdue']);
            if($result === false){
                return false;
            }
        }

        //修改保单数据为历史
        if(isset($user_data['is_policy'])){
            $result = self::setMaterialHistory($user_id,self::MATERIAL_POLICY,$user_data['is_policy']);
            if($result === false){
                return false;
            }
        }

        //修改车辆数据为历史
        if(isset($user_data['is_car'])){
            $result = self::setMaterialHistory($user_id,self::MATERIAL_CAR,$user_data['is_car']);
            if($result === false){
                return false;
            }
        }

        //修改贷款数据为历史
        if(isset($user_data['is_loan'])){
            $result = self::setMaterialHistory($user_id,self::MATERIAL_LOAN,$user_data['is_loan']);
            if($result === false){
                return false;
            }
        }

        $result = self::updateUser($user_id,$user_data);
        if($result === false){
            return false;
        }

        return true;
    }

    /**
     * 修改材料为历史
     * @param $user_id
     * @param $material_type
     * @param $status
     * @return bool|null
     */
    public static function setMaterialHistory($user_id,$material_type,$status){
        if(!in_array($material_type,[self::MATERIAL_ASSURE,self::MATERIAL_CAR,self::MATERIAL_COMPANY,self::MATERIAL_CREDIT_CARD,self::MATERIAL_HOUSE,self::MATERIAL_LOAN,self::MATERIAL_POLICY,self::MATERIAL_SHOP,self::MATERIAL_OVERDUE])){
            return false;
        }

        if(empty($status)){
            return false;
        }

        $user_field = 'is_'.$material_type;
        $user_info = IUserCache::getInfo($user_id);
        //注意：$status有特殊值或值相反时需要特殊处理  1:无对应资产;2:有对应资产
        if(isset($user_info[$user_field])) {
            $table = 'asset_'.$material_type;
            $where['user_id'] = $user_id;
            $where['is_history'] = IsHistory::not;
            if($material_type != self::MATERIAL_COMPANY){
                //公司信息无此字段
                $where['is_delete'] = IsDelete::No;
            }

            $data['is_history'] = IsHistory::yes;

            if($status == 1){
                //无对应资产
                if($status != $user_info[$user_field]){
                    if($material_type == self::MATERIAL_OVERDUE){
                        $result = self::updateUser($user_id,['overdue_info'=>['exp','null']]);
                    }else{
                        //将材料设为历史
                        $result = IDb::getInstance($table)->setDbWhere($where)->setDbData($data)->upd();
                    }

                    if($result === false){
                        return false;
                    }
                }else{
                    return null;
                }
            }else{
                //有对应资产
                if($status != $user_info[$user_field]){
                    if($material_type == self::MATERIAL_OVERDUE){
                        $result = true;
                        if(empty($user_info['overdue_info'])){
                            $result = false;
                        }
                    }else{
                        //查看是否真有对应资产
                        $result = IDb::getInstance($table)->setDbWhere($where)->row();
                    }

                    if(!$result){
                        $asset_type = self::$asset_map[$material_type] ?? '';
                        self::$error = '请填写'.$asset_type.'信息';
                        return false;
                    }
                }else{
                    return null;
                }
            }
        }else{
            return null;
        }

        return true;
    }

    /**
     * @功能 同步个人资产数据到用户数据
     * @param $user_id int 用户ID
     * @param $material_type string 个人资产类型
     * @param $status int 是否有对应资产
     * @开发者：gys
     * @return string
     */
    public static function syncMaterialToUserInfo($user_id,$material_type,$status = null){
        if(!in_array($material_type,[self::MATERIAL_ASSURE,self::MATERIAL_CAR,self::MATERIAL_COMPANY,self::MATERIAL_CREDIT_CARD,self::MATERIAL_HOUSE,self::MATERIAL_LOAN,self::MATERIAL_POLICY,self::MATERIAL_SHOP,self::MATERIAL_OVERDUE])){
            return false;
        }

        $user_field = 'is_'.$material_type;
        $user_info = IUserCache::getInfo($user_id);
        //判断要修改的字段是否存在
        if(!isset($user_info[$user_field])){
            return false;
        }


        if(!empty($status)){
            if($status == $user_info[$user_field]){
                //要修改的状态不变，直接返回
                return true;
            }
        }else{
            if($material_type == self::MATERIAL_OVERDUE){
                $status = IsOverdue::No; //无逾期
                $overdue_info = null;
                if(!empty($user_info['overdue_info'])){
                    $overdue_info = json_decode($user_info['overdue_info'],true);
                    foreach ($overdue_info as &$type){
                        if($type['less_30'] + $type['over_30'] + $type['over_60'] + $type['over_90'] > 0){
                            $type['is_overdue'] = IsOverdue::Yes;
                            $status = IsOverdue::Yes;
                        }else{
                            $type['is_overdue'] = IsOverdue::No;
                        }
                    }
                }
                if($status == IsOverdue::No){
                    $user_data['overdue_info'] = ['exp','null'];
                }else{
                    $user_data['overdue_info'] = json_encode($overdue_info);
                }
            }else{
                //未设置状态，检查对应资产表
                $table = 'asset_'.$material_type;
                $where['user_id'] = $user_id;
                $where['is_history'] = IsHistory::not;
                $where['is_delete'] = IsDelete::No;
                $is_exit = IDb::getInstance($table)->setDbWhere($where)->row();
                //注意：$status有特殊值或值相反时需要特殊处理
                if($is_exit){
                    $status = 2; //有对应资产
                }else{
                    $status = 1; //无对应资产
                }
            }
        }

        $user_data[$user_field] = $status;
        $result = self::updateUser($user_id,$user_data);
        if($result === false){
            return false;
        }

        return true;
    }

    /**
     * @功能 更新用户数据
     * @param $user_id int 用户编号
     * @param $user_data array 用户数据
     * @开发者：gys
     * @return string
     */
    public static function updateUser($user_id,$user_data){
        if(isset($user_data['is_marry'])){
            if($user_data['is_marry'] == IsMarry::divorce){
                //离异
                $user_data['couple_name'] = ['exp','null'];
                $user_data['couple_phone'] = ['exp','null'];
                $user_data['couple_identity'] = ['exp','null'];
            }else if($user_data['is_marry'] == IsMarry::unmarried){
                //未婚
                $user_data['is_marry'] = IsMarry::unmarried;
                $user_data['couple_name'] = ['exp','null'];
                $user_data['couple_phone'] = ['exp','null'];
                $user_data['couple_identity'] = ['exp','null'];
                $user_data['children_num'] = ['exp','null'];
            }
        }

        $user_upd = IDb::getInstance("user")->setDbWhere(['user_id'=>$user_id])->setDbData($user_data)->upd();
        if($user_upd === false){
            return false;
        }

        //清除缓存
        IUserCache::deleteInfo($user_id);

        return true;
    }

    /**
     * @功能 过滤用户数据，防止信息泄漏
     * @param $user_info array 用户数据
     * @开发者：gys
     * @return array
     */
    public static function filterUserInfo($user_info){

        //设置姓名信息
        if(isset($user_info['real']) && !empty($user_info['real'])){
            $user_info['real'] = get_string_rsa($user_info['real'],1);
        }

        //设置身份证信息
        if(isset($user_info['identity']) && !empty($user_info['identity'])){
            $user_info['identity'] = get_string_rsa($user_info['identity'],5,8);
        }

        //设置配偶身份证信息
        if(isset($user_info['couple_identity']) && !empty($user_info['couple_identity'])){
            $user_info['couple_identity'] = get_string_rsa($user_info['couple_identity'],5,8);
        }

        //用户密码信息
        if(isset($user_info['pwd'])){
            unset($user_info['pwd']);
        }
        //用户支付密码信息
        if(isset($user_info['pay_pwd'])){
            unset($user_info['pay_pwd']);
        }

        return $user_info;
    }

    /**
     * @功能 获取星号掩盖后的个人材料信息
     * @param $user_id int 用户ID
     * @开发者：gys
     * @return array
     */
    public static function getCoveredMaterial($user_id){
        //取得公司信息
        $material['company_info'] = [];
        $user_company_where['user_id'] = $user_id;
        $user_company_where['is_history'] = IsHistory::not;
        $user_company_info = IDb::getInstance("user_company")->setDbWhere($user_company_where)->row();
        if(!empty($user_company_info)){
            $material['company_info']['company_name'] = get_string_rsa($user_company_info['company_name'],0,intval(mb_strlen($user_company_info['company_name'])/2)) ?: '--';
            $material['company_info']['law_man'] = get_string_rsa($user_company_info['law_man'],1) ?: '--';
            $material['company_info']['phone'] = get_string_rsa($user_company_info['phone'],3,4) ?: '--';
            $material['company_info']['license_address'] = get_string_rsa($user_company_info['license_address'],intval(mb_strlen($user_company_info['company_name'])/2)) ?: '--';
            $material['company_info']['register_date'] = $user_company_info['register_date'] ?: '--';
            $material['company_info']['office_address'] = get_string_rsa($user_company_info['office_address'],intval(mb_strlen($user_company_info['company_name'])/2)) ?: '--';
            $material['company_info']['manager'] = get_string_rsa($user_company_info['manager'],1) ?: '--';
            $material['company_info']['tel'] = get_string_rsa($user_company_info['tel'],3,6) ?: '--';
            $material['company_info']['employee_num'] = $user_company_info['employee_num'] ?: '--';
            $material['company_info']['flow_out'] = $user_company_info['flow_out'] ?: '--';
            $material['company_info']['flow_in'] = $user_company_info['flow_in'] ?: '--';
        }

        //取得车辆列表
        $material['car_list'] = [];
        $user_car_where['is_delete'] = IsDelete::No;
        $user_car_where['is_history'] = IsHistory::not;
        $user_car_where['user_id'] = $user_id;
        $user_car_list = IDb::getInstance("user_car")->setDbWhere($user_car_where)->setDbOrder("user_car_id desc")->sel();

        //判断车辆是否存在
        if(!empty($user_car_list) && is_array($user_car_list) && count($user_car_list) > 0) {
            //整理数据
            foreach($user_car_list as $data){
                $temp = [];
                if($data['holder_type'] != HolderType::Other){
                    if(isset(HtmlEnumValue::$enum_value['holder_type'][$data['holder_type']])){
                        $temp['holder_name'] = HtmlEnumValue::$enum_value['holder_type'][$data['holder_type']];
                    }else{
                        $temp['holder_name'] = '--';
                    }
                }else{
                    $temp['holder_name'] = get_string_rsa($data['holder_name'],1) ?: '--';
                }

                $temp['car_brand_name'] = Name::car_brand($data['car_brand_id']) ?: '--';
                $temp['car_model_name'] = Name::car_model($data['car_model_id']) ?: '--';
//                $temp['car_config_name'] = Name::car_config($data['car_config_id']);
                $temp['car_money'] = $data['car_money'] ?: '--';
                $temp['run_mileage'] = $data['run_mileage'] ?: '--';
                if($data['pay_type'] == AssetPayType::full){
                    $temp['pay_type_name'] = '全款车';
                }else if($data['pay_type'] == AssetPayType::installment){
                    $temp['pay_type_name'] = '按揭车';
                }else{
                    $temp['pay_type_name'] = '--';
                }
                $temp['pay_type'] = $data['pay_type'];
                $temp['full_use_year'] = $data['full_use_year'] ?: '--';
                $temp['installment_loan_money'] = $data['installment_loan_money'] ?: '--';
                $temp['installment_month_repay'] = $data['installment_month_repay'] ?: '--';
                $temp['installment_loan_cycle'] = $data['installment_loan_cycle'] ?: '--';
                $temp['installment_repay_count'] = $data['installment_repay_count'] ?: '--';
                $temp['installment_handling_bank'] = $data['installment_handling_bank'] ?: '--';

                $material['car_list'][] = $temp;
            }
        }

        //判断信用卡是否存在
        $material['credit_card_info'] = [];
        $user_credit_card_where['is_delete'] = IsDelete::No;
        $user_credit_card_where['is_history'] = IsHistory::not;
        $user_credit_card_where['user_id'] = $user_id;
        $user_credit_info = IDb::getInstance("user_credit_card")
            ->setDbFiled("count(user_credit_card_id) as card_num,sum(amount) as total_amount,max(amount) as max_amount,sum(used_amount) as used_amount")
            ->setDbWhere($user_credit_card_where)
            ->setDbOrder("user_credit_card_id")
            ->row();
        if(!empty($user_credit_info)){
            if($user_credit_info['card_num'] > 0){
                $material['credit_card_info']['card_num'] = $user_credit_info['card_num'];
                //转化单位万
                $material['credit_card_info']['total_amount'] = bcdiv($user_credit_info['total_amount'],10000,2);
                $material['credit_card_info']['max_amount'] = bcdiv($user_credit_info['max_amount'],10000,2);
                $material['credit_card_info']['used_amount'] = bcdiv($user_credit_info['used_amount'],10000,2);
            }else{
                $material['credit_card_info'] = [];
            }
        }

        //判断房产是否存在
        $material['house_list'] = [];
        $user_house_where['is_delete'] = IsDelete::No;
        $user_house_where['is_history'] = IsHistory::not;
        $user_house_where['user_id'] = $user_id;
        $user_house_list = IDb::getInstance("user_house")->setDbWhere($user_house_where)->setDbOrder("user_house_id")->sel();
        if(!empty($user_house_list) && is_array($user_house_list)){
            //设置省市区
            foreach($user_house_list as $data){
                $temp = [];
                if($data['holder_type'] != HolderType::Other){
                    if(isset(HtmlEnumValue::$enum_value['holder_type'][$data['holder_type']])){
                        $temp['holder_name'] = HtmlEnumValue::$enum_value['holder_type'][$data['holder_type']];
                    }else{
                        $temp['holder_name'] = get_string_rsa($data['holder_name'],1) ?: '--';
                    }
                }else{
                    $temp['holder_name'] = get_string_rsa($data['holder_name'],1) ?: '--';
                }

                if($data['house_type'] != HouseType::other){
                    if(isset(HtmlEnumValue::$enum_value['house_type'][$data['house_type']])){
                        $temp['house_type_name'] = HtmlEnumValue::$enum_value['house_type'][$data['house_type']];
                    }else{
                        $temp['house_type_name'] = '--';
                    }
                }else{
                    $temp['house_type_name'] = $data['house_type_name'] ?: '--';
                }

                $province = Name::area($data['province_id']);
                $city = Name::area($data['city_id']);
                if($province == $city){
                    $temp['address'] = $province;
                }else{
                    $temp['address'] = $province.$city;
                }
                $temp['address'] .= Name::area($data['area_id']);
                $temp['area'] = $data['area'] ?: '--';
                $temp['price'] = $data['price'] ?: '--';
                if($data['pay_type'] == AssetPayType::full){
                    $temp['pay_type_name'] = '全款房';
                }else if($data['pay_type'] == AssetPayType::installment){
                    $temp['pay_type_name'] = '按揭房';
                }else{
                    $temp['pay_type_name'] = '--';
                }
                $temp['pay_type'] = $data['pay_type'];
                $temp['full_service_life'] = $data['full_service_life'] ?: '--';
                $temp['installment_loan_money'] = $data['installment_loan_money'] ?: '--';
                $temp['installment_month_repay'] = $data['installment_month_repay'] ?: '--';
                $temp['installment_loan_cycle'] = $data['installment_loan_cycle'] ?: '--';
                $temp['installment_repay_count'] = $data['installment_repay_count'] ?: '--';
                $temp['installment_handling_bank'] = $data['installment_handling_bank'] ?: '--';

                $material['house_list'][] = $temp;
            }
        }

        //判断贷款是否存在
        $material['loan_list'] = [];
        $user_loan_where['is_delete'] = IsDelete::No;
        $user_loan_where['is_history'] = IsHistory::not;
        $user_loan_where['user_id'] = $user_id;;
        $user_loan_list = IDb::getInstance("user_loan")->setDbWhere($user_loan_where)->setDbOrder("user_loan_id")->sel();
        if(!empty($user_loan_list) && is_array($user_loan_list)){
            foreach ($user_loan_list as $val){
                $temp = [];
                if($val['loan_type'] != LoanType::other){
                    if(isset(HtmlEnumValue::$enum_value['loan_type'][$val['loan_type']])){
                        $temp['loan_type_name'] = HtmlEnumValue::$enum_value['loan_type'][$val['loan_type']];
                    }else{
                        $temp['loan_type_name'] = '--';
                    }
                }else{
                    $temp['loan_type_name'] = $val['loan_type_name'] ?: '--';
                }
                $temp['loan_money'] = $val['loan_money'] ?: '--';
                $temp['loan_time'] = $val['loan_time'] ?: '--';
                $temp['loan_cycle'] = $val['loan_cycle'] ?: '--';
                $temp['repay_amount'] = $val['repay_amount'] ?: '--';
                $temp['settle_time'] = $val['settle_time'] ?: '--';
                if($val['is_overdue'] == IsOverdue::Yes){
                    $temp['is_overdue'] = '是';
                }else{
                    $temp['is_overdue'] = '否';
                }

                $material['loan_list'][] = $temp;
            }
        }

        //判断保单是否存在
        $material['policy_list'] = [];
        $user_policy_where['is_delete'] = IsDelete::No;
        $user_policy_where['is_history'] = IsHistory::not;
        $user_policy_where['user_id'] = $user_id;;
        $user_policy_list = IDb::getInstance("user_policy")->setDbWhere($user_policy_where)->setDbOrder("user_policy_id")->sel();
        if(!empty($user_policy_list) && is_array($user_policy_list)){
            foreach ($user_policy_list as $data){
                $temp = [];
                $temp['company_name'] = $data['company_name'] ?: '--';
                $temp['insured_name'] = get_string_rsa($data['insured_name'],1) ?: '--';
                if(isset(HtmlEnumValue::$enum_value['pay_type'][$data['pay_type']])){
                    $temp['pay_type_name'] = HtmlEnumValue::$enum_value['pay_type'][$data['pay_type']];
                }else{
                    $temp['pay_type_name'] = '--';
                }
                $temp['pay_money'] = $data['pay_money'] ?: '--';
                if(isset(HtmlEnumValue::$enum_value['policy_type'][$data['policy_type']])){
                    $temp['policy_type_name'] = HtmlEnumValue::$enum_value['policy_type'][$data['policy_type']];
                }else{
                    $temp['policy_type_name'] = '--';
                }
                $material['policy_list'][] = $temp;
            }
        }

        //判断网店是否存在
        $material['shop_list'] = [];
        $user_shop_where['is_delete'] = IsDelete::No;
        $user_shop_where['is_history'] = IsHistory::not;
        $user_shop_where['user_id'] = $user_id;
        $user_shop_list = IDb::getInstance("user_shop")->setDbWhere($user_shop_where)->setDbOrder("user_shop_id")->sel();
        if(!empty($user_shop_list) && is_array($user_shop_list)){
            foreach ($user_shop_list as $val){
                $temp = [];
                $temp['shop_url'] = $val['shop_url'] ?: '--';
                $temp['shop_flow'] = $val['shop_flow'] ?: '--';
                if(isset(HtmlEnumValue::$enum_value['business_year'][$val['business_year']])){
                    $temp['business_year_name'] = HtmlEnumValue::$enum_value['business_year'][$val['business_year']];
                }else{
                    $temp['business_year_name'] = '--';
                }

                $material['shop_list'][] = $temp;
            }
        }

        return $material;
    }

    /**
     * 获取信息完成度
     * @param $user_id
     * @return bool|int
     */
    public static function getMaterialPercent($user_id){
        //取得用户信息
        $user_info = IDb::getInstance('user')
            ->setDbFiled('phone,real,identity,identity_front_url,identity_back_url,police_station,identity_expire,birth_address,domicile_address,work_address,occupation,is_marry,couple_name,couple_phone,couple_identity,children_num,is_social,is_accumulation_fund,is_white,is_loan,is_overdue,is_student,is_car,is_house,is_credit_card,is_policy,is_company,is_assure,is_shop,is_court')
            ->setDbWhere(['user_id'=>$user_id])
            ->row();
        if(empty($user_info)){
            return false;
        }

        //判断数据完善程度
        $data_flg = 0;
        foreach($user_info as $value){
            if(!empty($value)){
                $data_flg++;
            }
        }

        //判断数据完善程度
        $material = ($data_flg / count($user_info)) * 100;
        if($material < 60){
            $material = rand(60,70);
        }else if($material > 100){
            $material = 100;
        }

        return $material;
    }

    /**
     * 修改用户意向等级，并修改客户池状态
     * @param $user_id
     * @param $intention_level
     * @param $agent_admin_id
     * @return bool
     */
    public static function setUserIntentionLevel($user_id,$intention_level,$agent_admin_id){
        if(!in_array($intention_level,[UserIntentionLevel::A,UserIntentionLevel::B,UserIntentionLevel::C])){
            return false;
        }

        $result = self::updateUser($user_id,['intention_level'=>$intention_level]);
        if(!$result){
            return false;
        }


        //之前状态为【不投放】并且意向等级修改为【C类】，则改为【未投放】
        if($intention_level == UserIntentionLevel::C){
            //判断客户池是否已经存在
            $user_pool_claim_where['user_id'] = $user_id;
            $user_pool_claim_where['pool_vie_status'] = PoolVieStatus::HaveEntered;
            $user_pool_claim_info = IDb::getInstance("user_pool_vie")->setDbWhere($user_pool_claim_where)->row();
            if($user_pool_claim_info === false){
                return false;
            }

            if(!empty($user_pool_claim_info)){
                $user_pool_claim_where['user_pool_vie_id'] = $user_pool_claim_info['user_pool_vie_id'];

                $user_pool_claim_data['pool_vie_status'] = PoolVieStatus::ToPriced;

                $user_pool_claim_upd = IDb::getInstance("user_pool_vie")->setDbData($user_pool_claim_data)->setDbWhere($user_pool_claim_where)->upd();
                if ($user_pool_claim_upd === false) {
                    return false;
                }
            }
        }

        ILog::UserLog($user_id,"修改用户意向等级为：".HtmlEnumValue::$enum_value['user_intention_level'][$intention_level],$agent_admin_id);

        return true;
    }

    /**
     * 申请额度审核
     * @param $user_id
     * @param $intention_amount
     * @param $intention_cycle
     * @param $apply_agent_admin
     * @return bool|null
     */
    public static function evaluateApply($user_id,$intention_amount,$intention_cycle,$apply_agent_admin){

        $where['user_id'] = $user_id;
        $where['audit_status'] = AuditStatus::Wait;
        $is_exist = IDb::getInstance('user_evaluate')->setDbWhere($where)->row();
        if($is_exist){
            //已存在审核中申请
            return null;
        }

        //修改之前的记录为历史
        $where = null;
        $where['user_id'] = $user_id;
        $update_data['is_history'] = IsHistory::yes;
        $result = IDb::getInstance('user_evaluate')->setDbData($update_data)->setDbWhere($where)->upd();
        if($result === false){
           return false;
        }

        //添加新申请
        $data['user_id'] = $user_id;
        $data['intention_amount'] = $intention_amount;
        $data['intention_cycle'] = $intention_cycle;
        $data['apply_agent_admin'] = $apply_agent_admin;
        $result = IDb::getInstance('user_evaluate')->setDbData($data)->add();
        if(!$result){
            return false;
        }

        return true;
    }

    /**
     * 获取用户等级
     * @param $user_id
     * @return string
     */
    public static function getUserPoolLevel($user_id){
        $user_data = IUserCache::getInfo($user_id);

        //判断用户级别
        if($user_data['is_white'] == IsWhite::No || $user_data['is_student'] == IsStudent::Yes){ //学生和黑户强制设置为C类客户
            $pool_level = PoolLevel::C;
        }else{
            //判断是否有车、有房或者有保单
            if($user_data['is_house'] == IsHouse::Yes || ($user_data['is_policy'] == IsPolicy::Yes && $user_data['is_car'] == IsCar::Yes)){
                $pool_level = PoolLevel::A;//A类客户
            }else{
                //判断是否有信用卡、社保、公积金、公司
                if($user_data['is_policy'] == IsPolicy::Yes || $user_data['is_car'] == IsCar::Yes || $user_data['is_credit_card'] == IsCreditCard::Yes || $user_data['is_social'] == IsSocial::Yes || $user_data['is_company'] == IsCompany::Yes  || $user_data['is_accumulation_fund'] == IsAccumulationFund::Yes){
                    $pool_level = PoolLevel::B;//B类客户
                }else{
                    $pool_level = PoolLevel::C;//C类客户
                }
            }
        }

        return $pool_level;
    }

    /**
     * 添加到客户池
     * @param $user_id
     * @param $province_id
     * @param $city_id
     * @param $money
     * @param $period
     * @param $bid_end
     * @param $purpose
     * @param $cooperate_id
     * @param $cooperate_admin_id
     * @return bool|mixed
     */
    public static function addToBidPool($user_id,$province_id,$city_id,$money,$period,$bid_end,$purpose = '',$cooperate_id=null,$cooperate_admin_id=null){
        $claim_data['money'] = floatval($money);
        $claim_data['period'] = intval($period);
        if($claim_data['period'] <= 0){
            self::$error = '贷款周期必须大于0';
            return false;
        }

        if($bid_end){
            $bid_end .= ' 23:59:59';
            $end_time = strtotime($bid_end);
            if(!$end_time){
                self::$error = '截止日期不正确';
                return false;
            }

            if($end_time <= time()){
                self::$error = '截止日期不能小于当前时间';
                return false;
            }
        }

        //TODO 能否同时发布多订单
//        $where_exist['user_id'] = $user_id;
//        $old_info = IDb::getInstance('user_pool_bid')->setDbWhere($where_exist)->row();
//        if(!empty($old_info)){
//            return $old_info['user_pool_bid_id'];
//        }

        //判断用户等级
//        $claim_data['material']= User::getMaterialPercent($user_id); // 资料完善程度（1~100）


        $claim_data['province_id'] = $province_id;
        $claim_data['city_id'] = $city_id;
        $claim_data['user_id'] = $user_id;
        $claim_data['period'] = $period;
        $claim_data['purpose'] = $purpose;

        if(!empty($cooperate_id)){
            $claim_data['user_pool_bid_type'] = UserPoolBidType::Cooperate;
            $claim_data['cooperate_id'] = $cooperate_id;
            $claim_data['cooperate_admin_id'] = $cooperate_admin_id;
            $claim_data['pool_bid_status'] = PoolBidStatus::Bid;
            $claim_data['bid_start'] = get_date_time();
            $claim_data['bid_end'] = $bid_end;
        }else{
            $claim_data['user_pool_bid_type'] = UserPoolBidType::Intent;
        }
        IDb::dbStartTrans();
        $bid_id = IDb::getInstance('user_pool_bid')->setDbData($claim_data)->add();
        if(!$bid_id){
            IDb::dbRollback();
            self::$error = '添加到客户池失败';
            return false;
        }

        $bid_no = $bid_id;
        if($bid_id < 100000){
            $bid_no += 100000;
        }
        $result = IDb::getInstance('user_pool_bid')->setDbData(['bid_no'=>$bid_no])->setDbWhere(['user_pool_bid_id'=>$bid_id])->upd();
        if(!$result){
            IDb::dbRollback();
            self::$error = '添加到客户池失败';
            return false;
        }

        IDb::dbCommit();
        return $bid_id;
    }

    public static function getAsset($user_id,$cover = false){

        $user_info = IUserCache::getInfo($user_id,['real','age','sex','birthday','identity','education','birth_address','is_marry','phone','loan_phone','couple_name','couple_phone','domicile_address','occupation','work_address','monthly_income',
            'is_credit_card','is_house','is_car','is_policy','is_loan','is_company','is_accumulation_fund','is_social','is_court','is_overdue','overdue_info']);
        if($user_info['real'] === false){
            self::$error = '用户不存在';
            return false;
        }
        if($cover){
            $user_info['real'] = get_real_cover($user_info['real'],$user_info['sex']);
        }

        $user_info['sex_text'] = get_enum_name('sex',$user_info['sex']);

        $user_info['identity'] = get_string_rsa($user_info['identity'],4,10);
        if(isset($user_info['birth_address'])) $user_info['birth_address'] = get_string_rsa($user_info['birth_address'],5);
        if(isset($user_info['work_address'])) $user_info['work_address'] = get_string_rsa($user_info['work_address'],5);
        if(isset($user_info['domicile_address'])) $user_info['domicile_address'] = get_string_rsa($user_info['domicile_address'],5);

        $user_info['is_marry_text'] = get_enum_name('is_marry',$user_info['is_marry']);
        $user_info['occupation_text'] = get_enum_name('occupation',$user_info['occupation']);
        $user_info['education_text'] = get_enum_name('education',$user_info['education']);

        //公司信息
        $company_info = [];
        if($user_info['is_company'] == IsCompany::Yes){
            $company_where['is_history'] = IsHistory::not;
            $company_where['user_id'] = $user_id;
            $company_info = IDb::getInstance("asset_company")->setDbWhere($company_where)->row();
            if(empty($company_info) || !is_array($company_info)){
                $company_info = array();
            }else if($cover){
                $company_info['company_type_text'] = get_enum_name('company_type',$company_info['company_type']);

                $company_info['company_name'] = get_string_rsa($company_info['company_name'],2,5);
                $company_info['law_man'] = get_string_rsa($company_info['law_man'],1,3);
                $company_info['manager'] = get_string_rsa($company_info['manager'],1,3);
                $company_info['phone'] = get_string_rsa($company_info['phone'],3,5);
                $company_info['website_url'] = get_string_rsa($company_info['website_url'],4,5);
                $company_info['license_address'] = get_string_rsa($company_info['license_address'],4,0);
                $company_info['office_address'] = get_string_rsa($company_info['office_address'],4,0);
                unset($company_info['licence_url']);
            }
        }

        //房产信息
        $user_house_list = [];
        if($user_info['is_house'] == IsHouse::Yes) {
            $user_house_where['is_delete'] = IsDelete::No;
            $user_house_where['is_history'] = IsHistory::not;
            $user_house_where['user_id'] = $user_id;
            $user_house_list = IDb::getInstance("asset_house")->setDbWhere($user_house_where)->setDbOrder("user_house_id")->sel();
            if (empty($user_house_list) || !is_array($user_house_list)) {
                $user_house_list = array();
            }

            foreach ($user_house_list as $key => $val) {
                $user_house_list[$key]['pay_type_text'] = get_enum_name('asset_pay_type', $val['pay_type']);
                $user_house_list[$key]['installment_pay_type_text'] = get_enum_name('installment_pay_type', $val['installment_pay_type']);
                $user_house_list[$key]['is_mortgage_text'] = get_enum_name('is_mortgage', $val['is_mortgage']);
                $user_house_list[$key]['mortgage_pay_type_text'] = get_enum_name('installment_pay_type', $val['mortgage_pay_type']);
                $user_house_list[$key]['house_type_name'] = get_enum_name('house_type', $val['house_type']);

                if($cover){
                    $val['holder_name'] = get_string_rsa($val['holder_name'],1,0);
                    $val['address'] = get_string_rsa($val['address'],3,0);
                }

                if ($val['holder_type'] != HolderType::Other) {
                    $user_house_list[$key]['holder_name'] = get_enum_name('holder_type', $val['holder_type']);
                }
            }
        }
        //信用卡信息
        $card_info = [];
        if($user_info['is_credit_card'] == IsCreditCard::Yes){
            $user_credit_card_where['is_delete'] = IsDelete::No;
            $user_credit_card_where['is_history'] = IsHistory::not;
            $user_credit_card_where['user_id'] = $user_id;
            $user_credit_card_list = IDb::getInstance("asset_credit_card")->setDbWhere($user_credit_card_where)->setDbOrder("user_credit_card_id")->sel();
            if(empty($user_credit_card_list) || !is_array($user_credit_card_list)){
                $user_credit_card_list = array();
            }

            $card_num = 0; // 卡数量
            $card_total_amount = 0; // 卡总额度
            $card_max_amount = 0; // 单卡最高额度
            $card_used_amount = 0; // 已使用总额度

            //取得用户银行卡所在用户
            foreach($user_credit_card_list as &$data){
                if(!empty($data['bank_id'])) $data['bank_name'] = Name::bank($data['bank_id']);

                if($data['amount'] > $card_max_amount){
                    $card_max_amount = $data['amount'];
                }

                $card_num += 1;
                $card_total_amount = bcadd($card_total_amount,$data['amount'],2);
                $card_used_amount = bcadd($card_used_amount,$data['used_amount'],2);
            }

            //转化单位万
            $card_info = [
                'card_num'=>$card_num,
                'total_amount'=>bcdiv($card_total_amount,10000,2),
                'max_amount'=>bcdiv($card_max_amount,10000,2),
                'used_amount'=>bcdiv($card_used_amount,10000,2),
            ];
        }

        //取得车辆列表
        $user_car_list = [];
        if($user_info['is_car'] == IsCar::Yes) {
            $user_car_where['is_delete'] = IsDelete::No;
            $user_car_where['is_history'] = IsHistory::not;
            $user_car_where['user_id'] = $user_id;
            $user_car_list = IDb::getInstance("asset_car")->setDbWhere($user_car_where)->setDbOrder("user_car_id desc")->sel();

            if(!empty($user_car_list) && is_array($user_car_list) && count($user_car_list) > 0) {
                //整理数据
                foreach($user_car_list as &$data){
                    $data['car_brand_name'] = Name::car_brand($data['car_brand_id']);
                    $data['car_model_name'] = Name::car_model($data['car_model_id']);
                    $data['car_config_name'] = Name::car_config($data['car_config_id']);

                    if($cover){
                        $data['holder_name'] = get_string_rsa($data['holder_name'],1,0);
                    }

                    if($data['holder_type'] != HolderType::Other){
                        if(isset(HtmlEnumValue::$enum_value['holder_type'][$data['holder_type']])){
                            $data['holder_name'] = HtmlEnumValue::$enum_value['holder_type'][$data['holder_type']];
                        }
                    }

                    $data['pay_type_text'] = get_enum_name('asset_pay_type',$data['pay_type']);
                    $data['is_mortgage_text'] = get_enum_name('is_mortgage',$data['is_mortgage']);
                    $data['mortgage_pay_type_text'] = get_enum_name('installment_pay_type',$data['mortgage_pay_type']);
                }
            }else{
                $user_car_list = array();
            }
        }

        //保单
        $user_policy_list = [];
        if($user_info['is_policy'] == IsPolicy::Yes) {
            $user_policy_where['is_delete'] = IsDelete::No;
            $user_policy_where['is_history'] = IsHistory::not;
            $user_policy_where['user_id'] = $user_id;
            $user_policy_list = IDb::getInstance("asset_policy")->setDbWhere($user_policy_where)->setDbOrder("user_policy_id")->sel();
            if (empty($user_policy_list) || !is_array($user_policy_list)) {
                $user_policy_list = array();
            }

            foreach ($user_policy_list as &$data) {
                $data['pay_type_name'] = get_enum_name('pay_type', $data['pay_type']);
                $data['policy_type_text'] = get_enum_name('policy_type', $data['policy_type']);

                if($cover){
                    $data['applicant_name'] = get_string_rsa($data['applicant_name'],1,0);
                    unset($data['img_url']);
                }
            }
        }
        //贷款
        $user_loan_list = [];
        if($user_info['is_loan'] == IsLoan::Yes) {
            $user_loan_where['is_delete'] = IsDelete::No;
            $user_loan_where['is_history'] = IsHistory::not;
            $user_loan_where['user_id'] = $user_id;
            $user_loan_list = IDb::getInstance("asset_loan")->setDbWhere($user_loan_where)->setDbOrder("user_loan_id")->sel();
            if (empty($user_loan_list) || !is_array($user_loan_list)) {
                $user_loan_list = array();
            }

            foreach ($user_loan_list as &$val) {
                if ($val['loan_type'] != LoanType::other) {
                    $val['loan_type_name'] = get_enum_name('loan_type', $val['loan_type']);
                }
            }
        }
        $return['user_info'] = $user_info;
        $return['company_info'] = $company_info;
        $return['user_house_list'] = $user_house_list;
        $return['credit_card_info'] = $card_info;
        $return['car_list'] = $user_car_list;
        $return['policy_list'] = $user_policy_list;
        $return['loan_list'] = $user_loan_list;
        $return['overdue_info'] = empty($user_info['overdue_info']) ? [] : json_decode($user_info['overdue_info'],true);

        return $return;
        
    }
}